<?php
namespace App\Services\WeChat;
use Icharle\Wxtool\Common;
use Icharle\Wxtool\Qrcode;
use Illuminate\Support\Facades\Storage;

/**
 * Created by PhpStorm.
 * User: yzy
 * Date: 2019/8/1
 * Time: 15:23
 */
class MiniService extends Qrcode{

    private $wxappid;
    private $wxsecret;
    private $wxtokenurl;
    private $wxpicurl;
    private $get_wxacode;
    private $wxpicsite;


    /**
     * Qrcode constructor.
     * @param $wxappid string 小程序appid
     * @param $wxsecret string 小程序AppSecret
     * @param $wxtokenurl string 获取token_url
     * @param $wxpicurl string 获取小程序码_url
     * @param $wxpicsite string 获取小程序码位置
     */
    public function __construct()
    {
        parent::__construct();
        $this->wxappid = config('wxtool.wx_appid');
        $this->wxsecret = config('wxtool.wx_secret');
        $this->wxtokenurl = config('wxtool.wx_token_url');
        $this->wxpicurl = config('wxtool.wx_pic_url');
        $this->get_wxacode = config('wxtool.get_wxacode');
        $this->wxpicsite = config('wxtool.wx_pic_site');
    }

    public function getwxacode($path)
    {
        $url = sprintf($this->get_wxacode, $this->GetAccessToken());
        $params = array(
            "path" => $path,
        );
        $img = Common::curl($url, json_encode($params));        //请求获取图片二进制流

        if (strlen($img) < 1000) {
            return false;
        }

        return $this->WriteQrcode($img);                        //返回路径
    }

    /**
     * 写入图片文件
     * @param $imgstream  图片二进制流
     * @return bool|string
     * 返回保存路径
     */
    public function WriteQrcode($imgstream)
    {
        $savePath = public_path($this->wxpicsite);                       //图片路径
        //检查目录是否存在
        if (!is_dir($savePath)) {
            // 尝试创建目录
            if (!mkdir($savePath, 0755, true)) {
                return false;
            }
        }
        $filename = uniqid() . '.png';                          //图片命名
        $realpath = $this->wxpicsite . $filename;               //图片存储路径
        Storage::put($realpath, $imgstream);                    //二进制流保存成图片
        return '/uploadfiles'.$this->wxpicsite . $filename;             //返回保存路径
    }
}